package com.gxc.tree;

/**
 * 给你一个整数数组 nums ，其中元素已经按 升序 排列，请你将其转换为一棵  平衡  二叉搜索树。
 */
public class SortedArrayToBST {

    public class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
    }

    public TreeNode sortedArrayToBST(int[] nums) {
        int n = nums.length;
        return bst(nums, 0, n-1);
    }

    private TreeNode bst(int[] nums, int start, int end) {
        if (start == end) return new TreeNode(nums[start]);
        if (start > end) return null;

        int mid = (start + end)/2;
        TreeNode node = new TreeNode(nums[mid]);
        TreeNode left = bst(nums, start, mid-1);
        TreeNode right = bst(nums, mid+1, end);
        node.left = left;
        node.right = right;
        return node;
    }

}
